from django.http import HttpResponseBadRequest,JsonResponse
from django.shortcuts import render, HttpResponse
from django.views import View
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
# Create your views here.
from libs.yuntongxun.sms import CCP
from utils.response_code import RETCODE
from random import randint

class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')

class ImageView(View):
    def get(self,request):
        '''
                       步骤：
                       1、接收前端传递过来的uuid
                       2、判断uuid失分获取到
                       3、通过调用captcha来生成图片验证码（返回：图片内容和图片二进制）
                       4、将图片内容保存到redis中。uuid作为key，图片内容作为值，同时还需要设置一个过期时间
                       5、返回图片给前端
                       :param request:
                       :return:
               '''
        uuid = request.GET.get('uuid')
        if uuid is None:
            return HttpResponseBadRequest('没有获取到uuid')
        txt,image=captcha.generate_captcha()
        redis_conn = get_redis_connection('default')
        redis_conn.setex(name='img:%s' % uuid, time=300, value = txt)
        return HttpResponse(image,content_type='image/jpeg')


class SmsCodeView(View):
    def get(self,request):
        mobile = request.GET.get('mobile')
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        if not all([mobile,image_code,uuid]):
            return JsonResponse({"code":RETCODE.NECESSARYPARAMERR,"errmsg":'参数不全'})
        redis_conn = get_redis_connection()
        image_code_redis = redis_conn.get('img:%s' % uuid)
        if image_code_redis is None:
            return JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": '图片验证码不存在'})

        redis_conn.delete('img；%s' % uuid)
        if image_code!= image_code_redis.decode().lower():
            return JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": '图片验证码错误'})

        # 3、生成短信验证码：生成6位数验证码
        sms_code = '%06d' % randint(0, 999999)

        ccp = CCP()
        ccp.send_template_sms('17392927956', [sms_code, 5], 1)
        print(f'你的验证码是：{sms_code}')
        return JsonResponse({"code": RETCODE.OK, "errmsg": '短信发送成功'})
